package net.sppan.blog.controller.admin;


import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sppan.blog.common.JsonResult;
import net.sppan.blog.controller.BaseController;
import net.sppan.blog.entity.Check;
import net.sppan.blog.service.CheckService;

@Controller
@RequestMapping("/admin/check")
public class AdminCheckController extends BaseController {
	@Resource
	private CheckService checkService;

	@GetMapping("/index")
	public String index() {
		return "admin/check/index";
	}

	@PostMapping("/list")
	@ResponseBody
	public Page<Check> list() {
		PageRequest pageRequest = getPageRequest();
		Page<Check> page = checkService.findAll(pageRequest);
		return page;
	}

	@GetMapping("/form")
	public String form(@RequestParam(required = false) Long id, ModelMap map) {
		if (id != null) {
			Check check = checkService.findById(id);
			map.put("check", check);
		}
		return "admin/check/form";
	}

	@PostMapping("/save")
	@ResponseBody
	public JsonResult save(Check check) {
		try {
			check.setAuthor(getLoginUser());
			checkService.saveOrUpdate(check);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.fail(e.getMessage());
		}
		return JsonResult.ok();
	}

	@PostMapping("/{id}/change")
	@ResponseBody
	public JsonResult change(@PathVariable Long id, String type) {
		try {
			checkService.change(id, type);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.fail(e.getMessage());
		}
		return JsonResult.ok();
	}

	@PostMapping("/{id}/del")
	@ResponseBody
	public JsonResult delete(@PathVariable Long id) {
		try {
			checkService.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.fail(e.getMessage());
		}
		return JsonResult.ok();
	}
}
